<template>
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="部门名称" class="smart-query-form-item">
        <a-input style="width: 300px" v-model:value="keywords" placeholder="请输入部门名称" />
      </a-form-item>

      <!--      <a-form-item label="状态" class="smart-query-form-item">-->
      <!--        <SmartEnumSelect width="120px" enum-name="ZZB_ENABLE_STATUS_ENUM" v-model:value="queryForm.status" />-->
      <!--      </a-form-item>-->

      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button-group>
          <a-button v-privilege="'depart:list'" type="primary" @click="onSearch">
            <template #icon>
              <ReloadOutlined />
            </template>
            查询
          </a-button>
          <a-button v-privilege="'depart:list'" @click="resetQuery">
            <template #icon>
              <SearchOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
        <a-button v-privilege="'depart:insert'" type="primary" @click="addDepart" class="smart-margin-left20">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card size="small" :bordered="true">
    <a-table
      size="small"
      bordered
      :loading="tableLoading"
      rowKey="id"
      :columns="columns"
      :data-source="departTreeData"
      :defaultExpandAllRows="false"
      :defaultExpandedRowKeys="defaultExpandedRowList"
      :pagination="false"
    >
      <template #bodyCell="{ record, column, text }">
        <template v-if="column.dataIndex === 'status'">
          <a-switch
            :checked="text === ZZB_ENABLE_STATUS_ENUM.ENABLE_STATUS.value"
            @change="(checked) => handleStatusChangeConfirm(checked, record)"
            :loading="record.statusLoading"
          />
        </template>

        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button v-if="record.status" @click="addDepart(record)" v-privilege="'depart:insert'" type="link"> 添加下级 </a-button>
            <a-button v-if="!record.status" @click="updateDepart(record)" v-privilege="'depart:update'" type="link">编辑 </a-button>
            <a-button
              danger
              v-if="!record.status && record.id !== topDepartId"
              v-privilege="'depart:delete'"
              @click="deleteDepart(record.id)"
              type="link"
            >
              删除
            </a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!-- 添加编辑部门弹窗 -->
    <DepartFormModal ref="departFormModal" @refresh="queryDepartTree" />
  </a-card>
</template>

<script setup>
  import { onMounted, reactive, ref, createVNode } from 'vue'
  import { departApi } from '/src/api/system/b-operation/depart-api'
  import { message, Modal } from 'ant-design-vue'
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
  import _ from 'lodash'
  import { SmartLoading } from '/src/components/framework/smart-loading'
  import DepartFormModal from './components/depart-form-modal.vue'
  import { smartSentry } from '/src/lib/smart-sentry'
  import { ZZB_ENABLE_STATUS_ENUM } from '/src/constants/system/system-const.js'
  import dayjs from 'dayjs'

  const DEPARTMENT_PARENT_ID = '0000000000000'

  // -----------------------  筛选 ---------------------
  const keywords = ref('')

  // ----------------------- 部门树的展示 ---------------------
  const tableLoading = ref(false)

  const topDepartId = ref()
  // 所有部门列表
  const departList = ref([])
  // 部门树形数据
  const departTreeData = ref([])
  // 存放部门id和部门，用于查找
  const idInfoMap = ref(new Map())
  // 默认展开的行
  const defaultExpandedRowList = reactive([])

  const columns = ref([
    {
      title: '部门名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '部门成员',
      dataIndex: 'memberNum',
      key: 'memberNum',
      width: 100,
    },
    // {
    //   title: '负责人',
    //   dataIndex: 'managerName',
    //   key: 'managerName',
    //   width: 100,
    // },
    {
      title: '更新时间',
      dataIndex: 'uTime',
      key: 'uTime',
      customRender: (column) => dayjs(column.text).format('YYYY-MM-DD HH:mm:ss'),
      width: 180,
    },
    {
      title: '描述',
      dataIndex: 'desc',
      key: 'desc',
      width: 300,
    },
    {
      title: '启用',
      dataIndex: 'status',
      width: 50,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 200,
    },
  ])

  // ------------------------ 查询表单 ------------------------
  const queryFormState = {
    keywords: '',
    type: undefined,
    status: undefined,
    showManagerFlag: true,
  }
  const queryForm = reactive({ ...queryFormState })

  onMounted(() => {
    queryDepartTree()
  })

  // 查询部门列表并构建 部门树
  async function queryDepartTree() {
    try {
      tableLoading.value = true
      let res = await departApi.list(queryForm)
      let data = res.data

      data.forEach((e) => {
        idInfoMap.value.set(e.id, e)
      })

      departList.value = data
      departTreeData.value = buildDepartTree(data, DEPARTMENT_PARENT_ID)

      // 默认显示 最顶级ID为列表中返回的第一条数据的ID
      if (!_.isEmpty(departTreeData.value) && departTreeData.value.length > 0) {
        topDepartId.value = departTreeData.value[0].id
      }

      defaultExpandedRowList.value = []
      defaultExpandedRowList.push(topDepartId.value)
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  // 构建部门树
  function buildDepartTree(data, fDepartId) {
    let children = data.filter((e) => e.fDepartId === fDepartId) || []
    if (!_.isEmpty(children)) {
      children.forEach((e) => {
        e.children = buildDepartTree(data, e.id)
      })
      return children
    }
    return null
  }

  // 重置
  function resetQuery() {
    keywords.value = ''
    onSearch()
  }

  // 搜索
  function onSearch() {
    if (!keywords.value) {
      departTreeData.value = buildDepartTree(departList.value, DEPARTMENT_PARENT_ID)
      return
    }
    let originData = departList.value.concat()
    if (!originData) {
      return
    }
    // 筛选出名称符合的部门
    let filterDepart = originData.filter((e) => e.name.indexOf(keywords.value) > -1)
    let filterDepartList = []
    // 循环筛选出的部门 构建部门树
    filterDepart.forEach((e) => {
      recursionFilterDepart(filterDepartList, e.id, false)
    })
    departTreeData.value = buildDepartTree(filterDepartList, DEPARTMENT_PARENT_ID)
  }

  // 根据ID递归筛选部门
  function recursionFilterDepart(resList, id, unshift) {
    let info = idInfoMap.value.get(id)
    if (!info || resList.some((e) => e.id === id)) {
      return
    }
    if (unshift) {
      resList.unshift(info)
    } else {
      resList.push(info)
    }
    if (info.fDepartId && info.fDepartId !== 0) {
      recursionFilterDepart(resList, info.fDepartId, unshift)
    }
  }

  // ---------------------------- 状态修改 ----------------------------
  const handleStatusChangeConfirm = async (checked, record) => {
    Modal.confirm({
      title: '状态变更',
      icon: createVNode(ExclamationCircleOutlined),
      content: `确认修改"${record.name}"状态为${checked ? '启用' : '禁用'}`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        handleStatusChange(checked, record)
      },
    })
  }

  const handleStatusChange = async (checked, record) => {
    // 保存原始值用于错误回滚
    const originalStatus = record.status
    // 将布尔值转换为 0/1
    const targetStatus = checked ? ZZB_ENABLE_STATUS_ENUM.ENABLE_STATUS.value : ZZB_ENABLE_STATUS_ENUM.DISABLE_STATUS.value
    try {
      record.statusLoading = true

      const response = await departApi.updateStatus({ id: record.id, status: targetStatus })
      if (response && response.code === 200) {
        // 更新本地状态
        record.status = targetStatus
        message.success('状态更新成功')
      } else {
        message.error('状态更新失败')
        // 如果更新失败，恢复原状态
        record.status = originalStatus
      }
    } catch (e) {
      smartSentry.captureError(e)
      record.status = originalStatus
    } finally {
      record.statusLoading = false
    }
  }

  // ----------------------- 表单操作：添加部门/修改部门/删除部门/上下移动 ---------------------
  const departFormModal = ref()

  // 添加
  function addDepart(e) {
    let data = {
      id: 0,
      name: '',
      fDepartId: e.id || null,
    }
    departFormModal.value.showModal(data)
  }

  // 编辑
  function updateDepart(e) {
    departFormModal.value.showModal(e)
  }

  // 删除
  function deleteDepart(id) {
    Modal.confirm({
      title: '提醒',
      icon: createVNode(ExclamationCircleOutlined),
      content: '确定要删除该部门吗?',
      okText: '删除',
      okType: 'danger',
      async onOk() {
        SmartLoading.show()
        try {
          await departApi.delete({ id: id })
          await queryDepartTree()
        } catch (error) {
          smartSentry.captureError(error)
        } finally {
          SmartLoading.hide()
        }
      },
      cancelText: '取消',
      onCancel() {},
    })
  }
</script>

<style scoped lang="less"></style>
